import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import { getOrderAPI, type orderDataArr } from "../../api/order";

type orderState = {
    error: string | null,
    loading: boolean,
    orderList: orderDataArr[] | undefined,
    selectOrder: orderDataArr | undefined
}

const initialState: orderState = {
    error: null,
    loading: false,
    orderList: undefined,
    selectOrder: undefined
}

const orderSlice = createSlice({
    name: 'order',
    initialState,
    reducers: {
        selectOrderList(state, action) {
            state.selectOrder = action.payload
        },
        clearOrderError(state) {
            state.error = null
        }
    },
    extraReducers(builder) {
        builder
            .addCase(getOrder.pending, (state) => {
                state.error = null
                state.loading = true
            })
            .addCase(getOrder.fulfilled, (state, action) => {
                state.orderList = action.payload
                state.loading = false
            })
            .addCase(getOrder.rejected, (state, action) => {
                if (action.payload) {
                    state.error = action.payload
                } else {
                    state.error = "获取订单失败"
                }
                state.loading = false
            })
    },
})

export const orderReducer = orderSlice.reducer
export const { clearOrderError,selectOrderList } = orderSlice.actions

export const getOrder = createAsyncThunk<orderDataArr[], void, { rejectValue: string }>('order/getOrder', async (_, { rejectWithValue }) => {
    try {
        const res = await getOrderAPI()
        console.log(res)
        if (res.data.code === 200) {
            return res.data.data
        } else {
            return rejectWithValue(res.data.msg || '获取订单信息失败')
        }
    } catch (error) {
        return rejectWithValue(error + '' || "请求订单信息异常")
    }
})